﻿using System;

using Cognifide.PowerShell.Shell.Host;
using Cognifide.PowerShell.Shell.Settings;

using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.Sheer;

namespace Cognifide.PowerShell.SitecoreCommands
{
    [Serializable]
    public class ExecutePowerShellScript : Command
    {
        public override void Execute(CommandContext context)
        {
            string scriptId = context.Parameters["script"];
            string scriptDb = "core";
            Item scriptItem = Factory.GetDatabase(scriptDb).GetItem(new ID(scriptId));
            
            string warning = scriptItem["PreExecutionWarning"];
            string showResults = scriptItem["ShowResults"];
            string itemId = context.Items[0].ID.ToString();
            string itemDb = context.Items[0].Database.Name;

            if (!String.IsNullOrEmpty(warning))
            {
                ClientPipelineArgs clientArgs = new ClientPipelineArgs();
                clientArgs.Parameters.Add("script", scriptId);
                clientArgs.Parameters.Add("scriptDB", "core");
                clientArgs.Parameters.Add("item", itemId);
                clientArgs.Parameters.Add("itemDB", context.Items[0].Database.Name);
                clientArgs.Parameters.Add("showResults", showResults);
                clientArgs.Parameters.Add("warning", warning);
                Context.ClientPage.Start(this, "ConfirmScriptExecution", clientArgs);
            }
            else
            {
                ExecuteScript(itemId, itemDb, scriptId, scriptDb, showResults);
            }
        }

        public void ConfirmScriptExecution(ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (args.Result == "yes")
                {
                    ExecuteScript(args.Parameters["item"], args.Parameters["itemDB"], args.Parameters["script"], args.Parameters["scriptDB"], args.Parameters["showResults"]);
                }
            }
            else
            {
                Sitecore.Context.ClientPage.ClientResponse.Confirm(args.Parameters["warning"]);
                args.WaitForPostBack();
            }

        }

        public void ExecuteScript(string itemId, string itemDb, string scriptId, string scriptDb, string showResults)
        {
            if (showResults == "1")
            {
                Context.ClientPage.ClientResponse.Broadcast(
                    Context.ClientPage.ClientResponse.ShowModalDialog(
                        String.Format(
                            "/Console/Layouts/PowerShellResults.aspx?id={0}&db={1}&scriptId={2}&scriptDb={3}",
                            itemId,
                            itemDb,
                            scriptId,
                            scriptDb),
                            "800", "600", "Powershell Script Results", false), 
                        "Shell");
            }
            else
            {
                Item item = Factory.GetDatabase(itemDb).GetItem(new ID(itemId));
                Item scriptItem = Factory.GetDatabase(scriptDb).GetItem(new ID(scriptId));

                using (var scriptSession = new ScriptSession())
                {
                    scriptSession.ExecuteScriptPart("Set-HostProperty -HostWidth 80");
                    scriptSession.ExecuteScriptPart(PsConsoleSettings.Instance.PreScript);
                    scriptSession.ExecuteScriptPart(
                        String.Format(
                            "cd \"{0}:{1}\"", item.Database.Name, item.Paths.Path.Replace("/", "\\").Substring(9)));
                    scriptSession.ExecuteScriptPart(scriptItem["Script"]);

                }

            }
        }
    }
}
